import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:tiktokadult/assets_tool/app_colors.dart';
import 'package:tiktokadult/hj_model/mine/task_center_data.dart';
import 'package:tiktokadult/hj_utils/api_service/mine_service.dart';
import 'package:tiktokadult/hj_utils/global.dart';
import 'package:tiktokadult/hj_utils/widget_utils.dart';
import 'package:tiktokadult/tools_base/global_store/store.dart';
import 'package:tiktokadult/tools_base/widget/common_dialog.dart';
import 'package:tiktokadult/tools_base/widget/net_image_widget.dart';

import '../../../tools_base/loading/LoadingHelper.dart';
import '../mine_utils.dart';

class IntegralExchangeView extends StatefulWidget {
  final String? titleDesc;
  const IntegralExchangeView({super.key, this.titleDesc});

  @override
  State<IntegralExchangeView> createState() => _IntegralExchangeViewState();
}

class _IntegralExchangeViewState extends State<IntegralExchangeView> {
  final dataSouce = [];
  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addPostFrameCallback((timeStamp) async {
      final res = await MineService.fetchIntegralExchangeList();
      globalStore.refreshWallet();
      dataSouce.addAll(res);
      setState(() {});
    });
  }

  @override
  Widget build(BuildContext context) {
    if (dataSouce.isEmpty) return SizedBox.shrink();
    return Column(
      children: [
        Row(
          children: [
            Text(
              widget.titleDesc ?? '积分兑换',
              style: TextStyle(color: Colors.white, fontSize: 20.sp, fontWeight: FontWeight.w500),
            ),
            // Spacer(),
            // Consumer<GlobalStore>(
            //   builder: (_, store, __) => Text(
            //     '当前积分${store.wallet?.integral ?? 0}',
            //     style: TextStyle(color: Colors.white.withOpacity(.6), fontSize: 14.sp, fontWeight: FontWeight.w400),
            //   ),
            // ),
          ],
        ),
        14.h.sizeBoxH,
        GridView.builder(
          shrinkWrap: true,
          physics: NeverScrollableScrollPhysics(),
          gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
              crossAxisCount: 2, crossAxisSpacing: 10.w, mainAxisSpacing: 14.h, childAspectRatio: 154 / 111),
          itemCount: dataSouce.length,
          itemBuilder: (BuildContext context, int index) {
            final model = dataSouce[index];
            return Container(
              decoration: BoxDecoration(color: Color(0xff303030), borderRadius: BorderRadius.circular(9)),
              padding: EdgeInsets.only(left: 12.w, right: 12.w, top: 16.h, bottom: 9.h),
              width: double.infinity,
              height: double.infinity,
              child: Column(
                children: [
                  Expanded(
                    child: ClipRRect(
                      borderRadius: BorderRadius.vertical(top: Radius.circular(9)),
                      child: Stack(
                        alignment: Alignment.centerLeft,
                        children: [
                          NetworkImageLoader(
                            imageUrl: model.img ?? '',
                            borderRadius: 0,
                            width: double.infinity,
                            height: double.infinity,
                          ),
                          // Padding(
                          //   padding: EdgeInsets.symmetric(horizontal: 12),
                          //   child: Column(
                          //     crossAxisAlignment: CrossAxisAlignment.start,
                          //     mainAxisAlignment: MainAxisAlignment.center,
                          //     children: [
                          //       Text(
                          //         model.name ?? '',
                          //         maxLines: 1,
                          //         overflow: TextOverflow.ellipsis,
                          //         style: TextStyle(color: Colors.white, fontSize: 16.sp),
                          //       ),
                          //       Text(
                          //         model.desc ?? '',
                          //         maxLines: 1,
                          //         overflow: TextOverflow.ellipsis,
                          //         style: TextStyle(color: Color(0xffcccccc), fontSize: 10.sp),
                          //       )
                          //     ],
                          //   ),
                          // )
                        ],
                      ),
                    ),
                  ),
                  10.sizeBoxH,
                  Container(
                    // decoration: BoxDecoration(color: Color(0xff202133), borderRadius: BorderRadius.vertical(bottom: Radius.circular(9))),
                    child: Row(
                      children: [
                        Expanded(
                          child: Text(
                            '花费${model.price ?? 0}积分',
                            style: TextStyle(color: Color(0xFF989898), fontSize: 14.sp),
                          ),
                        ),
                        GestureDetector(
                          onTap: () => onExchange(model),
                          child: Container(
                            padding: EdgeInsets.symmetric(horizontal: 9.w, vertical: 3.h),
                            decoration: BoxDecoration(color: Color(0xffE1351F), borderRadius: BorderRadius.circular(11)),
                            child: Text(
                              '立即兑换',
                              style: TextStyle(color: Colors.white, fontSize: 12.sp),
                            ),
                          ),
                        )
                      ],
                    ),
                  )
                ],
              ),
            );
          },
        ),
        20.sizeBoxH,
        Divider(
          height: 1,
          color: Colors.white.withOpacity(.1),
        )
      ],
    );
  }

  onExchange(IntegralExchangeModel model) async {
    final hasIntegral = globalStore.wallet?.integral ?? 0;
    if (hasIntegral < (model.price ?? 0)) {
      showToast('积分不足，无法兑换～');
      return;
    }
    LoadingHelper.showLoading();
    final res = await MineService.integralExchangeSomething(model.id ?? '');
    LoadingHelper.dismissLoading();
    if (res) {
      if (model.type == 5) {
        Get.dialog(InputAddressAlert(model: model));
      } else {
        showToast('兑换成功～');
      }
      globalStore.refreshWallet();
    }
  }
}

class InputAddressAlert extends StatefulWidget {
  // final Function()? confirmCallback;
  final IntegralExchangeModel model;
  const InputAddressAlert({super.key, required this.model});

  @override
  State<InputAddressAlert> createState() => _InputAddressAlertState();
}

class _InputAddressAlertState extends State<InputAddressAlert> {
  final nameCtr = TextEditingController();
  final addressCtr = TextEditingController();
  final phoneCtr = TextEditingController();

  @override
  Widget build(BuildContext context) {
    return CommonDialog(
      child: Column(
        mainAxisSize: MainAxisSize.min,
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Text(
            '温馨提示',
            style: TextStyle(color: Color(0xffffffff), fontSize: 18.sp, fontWeight: FontWeight.w800),
          ),
          20.h.sizeBoxH,
          Divider(
            height: 1,
            color: Colors.white.withOpacity(.1),
          ),
          20.h.sizeBoxH,
          Container(
            width: double.infinity,
            height: 45.h,
            alignment: Alignment.center,
            padding: EdgeInsets.symmetric(horizontal: 13.w),
            child: Text(
              "兑换成功！",
              style: TextStyle(color: Color(0x8CFFFFFF), fontSize: 16),
              textAlign: TextAlign.center,
            ),
          ),
          5.h.sizeBoxH,
          Container(
            width: double.infinity,
            height: 55.h,
            alignment: Alignment.center,
            padding: EdgeInsets.symmetric(horizontal: 13.w),
            child: Text(
              "实物奖品请联系在线客服领取，填写收货地址等信息",
              style: TextStyle(color: Color(0x8CFFFFFF), fontSize: 16),
              textAlign: TextAlign.center,
            ),
          ),
          20.h.sizeBoxH,
          Padding(
            padding: EdgeInsets.symmetric(horizontal: 15.w),
            child: GestureDetector(
              onTap: () async {
                MineUtils.goCSPage();
              },
              child: Container(
                decoration: BoxDecoration(color: AppColors.actionRed, borderRadius: BorderRadius.circular(3)),
                height: 44,
                alignment: Alignment.center,
                child: Text(
                  '联系客服',
                  style: TextStyle(color: Colors.white, fontSize: 16, fontWeight: FontWeight.w500),
                ),
              ),
            ),
          )
        ],
      ),
    );
  }

  Widget _buildNormalInputView(String hint, TextEditingController controller, {int? maxLeng, List<TextInputFormatter>? inputFormatters}) {
    return TextField(
      maxLength: maxLeng,
      controller: controller,
      inputFormatters: inputFormatters,
      style: TextStyle(color: Colors.white, fontSize: 16.sp),
      decoration: InputDecoration(
        border: InputBorder.none,
        hintText: hint,
        counter: SizedBox.shrink(),
        isDense: true,
        contentPadding: EdgeInsets.zero,
        hintStyle: TextStyle(color: Color(0XFF999999), fontSize: 16.sp),
      ),
    );
  }
}
